/* 
Copyright (c) 2004,2005, 2006, 2007, 2008 University of Illinois 

All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

3. The name of the author may not be used to endorse or promote products
   derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
AccessibilityExtension.ns(function() { with (AccessibilityExtension.LIB) {

	var AE = AccessibilityExtension.ns;  
	AE.dialogName = 'accessext-form-list-headers';
	
	//var definedRoles = ['heading','region','main','secondary','navigation','banner','contentinfo','definition','note','seealso','search'];
	var definedRoles = ['application','banner','complementary','contentinfo','main','navigation','search'];
	
	function headerDisplayDetails() {};
	headerDisplayDetails.prototype = {
		dataElementNames : ['icita07', 'icita08', 'order', 'baseuri','level','role','text'],
		columnHeaders : ['column.header.icita07.label', 'column.header.icita08.label','column.header.order.label','column.header.baseuri.label', 'column.header.level.label','column.header.landmarkrole.label','column.header.text.label'],
		
		accessIssuesDataElementNames : ['toomanyfewh1','nonefound','impropernesting','nonefoundARIA','emptyheader', 'siblingDupName','toolong', 'headerOnlyAlt'], // ,'toomanymain'
		accessIssuesMessages : ['headers.warnings.toomanyfewh1','headers.warnings.nonefound','headers.warnings.impropernesting','headers.warnings.nonefoundARIA', 'headers.msg.emptyheader', 'headers.msg.siblingDupName', 'headers.msg.toolong', 'headers.msg.headerOnlyAlt'], //,'headers.msg.toomanymain'
	}
	var headerDisplayDetails = new headerDisplayDetails();
	
	function headerObject(torder, tnode) {
		this.order = torder;
		this.parseNode(tnode);
	};
	
	headerObject.prototype = {
		id : "",
		icita07 : "",
		icita08 : "",
		order : 0,
		baseuri : "",
		level : "",
		role : "",
		text : "",
		alt : "",
		node: null,
		positionOffScreen: false,
		relatednode: null,
		toomanyfewh1 : false,
		impropernesting : false,
		nonefound : false,
		nonefoundARIA : false,
		toomanymain : false,
		emptyheader : false,
		siblingDupName : false,
		toolong : false,
	   	headerOnlyAlt : false,
		display : true,
		displayDetails: headerDisplayDetails,
		getMainColumnText : function() {
			return this.text;
		},
		parseNode : function(node) {
			//the ARIA informtion is inserted by ParseDocument()
			this.id = GetValueFromAttributes(node,['id'],"");
			this.node = node;
			this.level = node.tagName.charAt(1);
			this.role = GetValueFromAttributes(node,['role'],"");
			this.baseuri = getBaseURI(node);
			this.positionOffScreen = PositionOffScreen(node); //can be changed by ParseDocumentForHeaders in aria cases
			this.text = cleanSpaces(getNodeText(node));
  			if (this.text == "") this.emptyheader = true;
  			
			//level 1 headers are checked in the title dialog
			if (this.level !='1' && this.text != '' && this.text == getDisplayableAltRecursively(node)) {this.headerOnlyAlt=true;}
			this.alt = GetUserAltFromNode(node);
			if (this.text.length > 60) {
				if (this.text.indexOf('{-ALT: ') == 0 ) { // test the text of the header only - appears after {IMG-ALT: }
					if (this.text.length - this.text.indexOf('}') > 60) {this.toolong = true;}
				} else {
					this.toolong = true;
				}
			}
			
			//impropernesting
			var tag =  node.tagName.toLowerCase();
			if (tag == 'h1' || tag == 'h2' || tag == 'h3' || tag == 'h4' || tag == 'h5' || tag == 'h6') {
				var xpathResult = node.ownerDocument.evaluate("following::h1", node, accessext_NSResolver, XPathResult.ANY_TYPE,null);
				var r = xpathResult.iterateNext();
				if (r == null && tag != 'h1') {
					var xpathResult = node.ownerDocument.evaluate("preceding::h" + parseInt(this.level-1), node, accessext_NSResolver, XPathResult.ANY_TYPE,null);
					var r = xpathResult.iterateNext();
					if (r == null) this.impropernesting = true;
				}
				//toomanyfewh1
				if (tag == 'h1') {
					var numH1s = node.ownerDocument.evaluate("count(//h1)", node.ownerDocument, accessext_NSResolver, XPathResult.ANY_TYPE,null).numberValue;
					if (numH1s > 2) this.toomanyfewh1 = true;
				}
			}
			
		},
		getTreeNode : function(windoc) {
			return accesxt_generateTreeboxResults(windoc,this);
		},
		
	}
AccessibilityExtension.LIB.extend(AccessibilityExtension.LIB,
{	
	newHeaderObject: function(torder, tnode) { 
		var n = new headerObject(torder, tnode);
		return n; 
	},

	post_InitAccessibilityExt: function() {
		accessext_setNoteText(0);
		try {
			AE.treebox.addEventListener('keypress',accessext_headerSearchOnKeyPress,true);
		} catch (ex) {
			accessext_consoleDump('Failed to add onkeypress event handler: ' + ex);
		}
	},
	
	ParseDocument: function(doc) {
		ParseDocumentForHeaders(doc, AE.dataarray);
	},
	
	ParseDocumentForHeaders: function(doc, loadArray) {
		try {
			var hasHTMLHeaders=false;	
			var countOfMain=0;	
			var xp;
			if (accessext_docUsesNamespace(doc)) {
				xp = "//html:h1|//html:h2|//html:h3|//html:h4|//html:h5|//html:h6";
			} else {
				xp = "//h1|//h2|//h3|//h4|//h5|//h6";
			}
			
			var xpathResult = doc.evaluate(xp, doc, accessext_NSResolver, XPathResult.ANY_TYPE,null);
			var r = xpathResult.iterateNext();
			while (r) {
				loadArray[loadArray.length] = new headerObject(loadArray.length + 1,r);
				r = xpathResult.iterateNext();
			}
			
			//SF 9/5/07 ARIA table of contents
			var relAttr = null;
			if (accessext_docUsesNamespace(doc)) {
				xp = "//html:link";
			} else {
				xp = "//link";
			}
			xpathResult = doc.evaluate(xp, doc, accessext_NSResolver, XPathResult.ANY_TYPE,null);
			r = xpathResult.iterateNext();
			while (r) {
				if (r.hasAttribute("rel")) {
					relAttr = GetValueFromAttributes(r,['rel'],"");
					if (relAttr != "" && definedRoles.indexOf(relAttr.toLowerCase()) != -1) {
						var existingNodeFound = false;
						var hrefAttr = GetValueFromAttributes(r,['href'],"");
						if (hrefAttr != "") {
							hrefAttr = hrefAttr.substring(1); //remove the # from the inpage link
							for (var i = loadArray.length - 1; i >= 0; i--) {
								if (loadArray[i].id == hrefAttr) {
									loadArray[i].role = relAttr;
									existingNodeFound = true;
								} 
							}
						} 								
						if (existingNodeFound == false) {				
							loadArray[loadArray.length] = new headerObject(loadArray.length + 1,r);
							var obj = loadArray[loadArray.length-1]; //headerObject(loadArray.length + 1, r); 
							obj.level = "";
							obj.alt = "";
							obj.role = relAttr;
							obj.text = cleanSpaces(GetValueFromAttributes(r,['title'],""));
							obj.relatednode = accessext_getnodebyid(doc,hrefAttr);
							if (obj.relatednode != null) {
							// SMF uncomment this to get the 'title' from the related node's text
								obj.text = cleanSpaces(GetValueFromAttributes(obj.relatednode,['title'],""));
							//	if (obj.text == "") { 
							//		obj.text = cleanSpaces(getNodeText(obj.relatednode));
							//	}
								obj.relatednode = accessext_getfirstvisiblenode(obj.relatednode);
								if (obj.positionOffScreen) obj.positionOffScreen=false;
							}
							if (obj.text == "") { 
								obj.text = accessext_getBundleSingleString('noTitle');
							}
						}
					}
				}
				r = xpathResult.iterateNext();
			}
			if (loadArray.length > 0){hasHTMLHeaders=true};		
	
			var found;
			xp = "//*[@x:role|@x2:role|@role]"; // "//*[@role]";
			xpathResult = doc.evaluate(xp, doc, accessext_NSResolver, XPathResult.ANY_TYPE,null);
			r = xpathResult.iterateNext();
			while (r) {
				if (r.hasAttribute("role")) {
					relAttr = GetValueFromAttributes(r,['role'],"");
		// KILL NAMESPACE CODE
		//			if (relAttr.indexOf(":") == -1 || relAttr.toLowerCase() == "wairole:heading" || relAttr.toLowerCase() == "wairole:region") { //we don't want to pick up items using wairole: etc.
		//			if (relAttr.toLowerCase() == "heading" || relAttr.toLowerCase() == "region") { //we don't want to pick up items using wairole: etc.
					for (var i = 0, found=false; i < definedRoles.length && !found; i++) {
						if (relAttr.toLowerCase() == definedRoles[i]) { found = true; }
					}
					if (found ) { 
						if (relAttr.toLowerCase() == "main") { countOfMain++; }
						var labelledby = GetValueFromAttributes(r,['aria-labelledby'],"");
						if (labelledby == "") { labelledby = GetValueFromAttributes(r,['labelledby'],""); }
						var txtValue = cleanSpaces(getNodeText(r));
						var existingNodeFound = false;
						for (var i = loadArray.length - 1; i >= 0; i--) {
							if (labelledby != "" && loadArray[i].id == labelledby) {
								loadArray[i].role = relAttr;
								existingNodeFound = true;
							} else { // check the node's text value
								if (txtValue == loadArray[i].text) {
									existingNodeFound = true;
								}
							}
						}
						
						if (existingNodeFound == false) {
							loadArray[loadArray.length] = new headerObject(loadArray.length + 1,r);
							
							var obj = loadArray[loadArray.length-1]; 
							obj.level = "";
							obj.alt = "";
							obj.role = GetValueFromAttributes(r,['role'],""); 
							if (labelledby != "") {	
								var returnArray = getTextAssociatedWithIDs(doc,labelledby, false);
								obj.text = returnArray[0]; //returntext
								if (returnArray[1] != null) {obj.text =+ ' ' + accessext_getBundleSingleString('undefinedLabelledby');} //returnnotfoundids
								obj.relatednode = returnArray[2]; //firstvisibleobjfound
							} else {
								obj.text = cleanSpaces(GetValueFromAttributes(r,['title'],""));
							}
							if (obj.text == "") { 
								if (txtValue == "") {
									obj.text = accessext_getBundleSingleString('noLabelledbyOrTitle');
								} else {
									obj.text = txtValue;
								}	
							}				
						}				
					}
				}
				r = xpathResult.iterateNext();
			}
			
			var numH1s = 0;
			for (var i = 0; i < loadArray.length; i++) {
				if (loadArray[i].level == "1") {numH1s++;}
				if (countOfMain > 1 && loadArray[i].role.toLowerCase() == "main") {	loadArray[i].toomanymain = true;	}
	/*			else if (loadArray[i].text.length > 60) {
					if (loadArray[i].text.indexOf('{-ALT: ') == 0 ) { // test the text of the header only - appears after {IMG-ALT: }
						if (loadArray[i].text.length - loadArray[i].text.indexOf('}') > 60) {loadArray[i].toolong = true;}
					} else {
						loadArray[i].toolong = true;
					}
				}
	*/
			}
			if (loadArray.length == 0 || !hasHTMLHeaders) {
				xp = "//html:body|//html:head|//body|//head"; //find anything on the page for the 'node'
				var xpathResult = doc.evaluate(xp, doc, accessext_NSResolver, XPathResult.ANY_TYPE,null);
				var r = xpathResult.iterateNext();
				loadArray[loadArray.length] = new headerObject(loadArray.length + 1,r);
				loadArray[loadArray.length-1].level = '';
				loadArray[loadArray.length-1].role = '';
				loadArray[loadArray.length-1].text = accessext_getBundleSingleString('none');
				loadArray[loadArray.length-1].nonefound = true;
				loadArray[loadArray.length-1].toomanyfewh1 = true;
				if (loadArray.length == 1 ) { // the one we just added
					loadArray[loadArray.length-1].nonefoundARIA = true;
				}
			} else {
				if (numH1s == 0) loadArray[0].toomanyfewh1 = true;
			}
	
			for (var i=0, j=0, n=loadArray.length; i<n; i++) {                    
				for (j=i+1; j<n; j++) {              
					if (loadArray[i].level == loadArray[j].level) {
						if (loadArray[i].text.toLowerCase()==loadArray[j].text.toLowerCase()) { //determine if siblings
							var sibs = true;
							for (var k=j; k > i && sibs; k--) {
								if (loadArray[j].level != loadArray[k].level) {	sibs = false;}
							}
							if (sibs) {loadArray[i].siblingDupName=loadArray[j].siblingDupName=true;}
						}
					}	
				}
			}
	
			setMaxSeverityForArray(loadArray);
			
		} catch (ex) {
			accessext_consoleDump('ParseDocumentForHeaders exception: ', ex);
		}
	},
	
	//by Bohdan R. Rau
	accessext_find_focusable: function(node)
	{
		var el;
		function is_focusable()
		{
			if (node.nodeName.toLowerCase() == "a" && typeof node.href != "undefined") return true;
			if (node.hasAttribute('tabindex')) return true;
			if (typeof node.tabindex != "undefined") return true;
			return false;
		}
		if (is_focusable()) return node;
		for (node=node.firstChild;node;node=node.nextSibling) if (node.nodeType == 1) {
			el=accessext_find_focusable(node);
			if (el) return el;
		}
		return null;
	},
	
	accessext_headersMoveToNode: function() {
		var theindex = AE.treebox.currentIndex;
		if (theindex  < 0) {
			return false;
		}
		var node = AE.dataarray[theindex].node;
		if (node == null) {
			alert('node is null');
			return false;
		}
		accessext_keyboardFocusNode(node,AE.thewindow);
		var el=accessext_find_focusable(node);   //by Bohdan R. Rau, if "tabindex" was set by extension, we should remove "tabindex" attribute from element when done 
		if (el) node=el;
		if (node.nodeName.toLowerCase()!='a' && !node.hasAttribute('tabindex') && typeof node.tabindex == "undefined") {
			node.setAttribute("tabindex","-1");
		}
		AE.thewindow.setTimeout(function() {node.focus();},200); 
		return true;	
	},
	
	selectTest: function(node) {
		var tempdoc = node.ownerDocument;
		var rv = tempdoc.createRange();
		rv.selectNode(node);
		var sel = AE.thewindow.getSelection();
		sel.removeAllRanges();
		sel.addRange(rv);
		sel.focusNode;
	},
	
	/*
	Dialog box constructor
	*/
	activation_custom: function(theIndex) {
		var node = AE.dataarray[theIndex].node;
		selectTest(node);
		return true;
	},
	
	accessext_headerSearchOnKeyPress: function(e) {
		return accessext_searchOnKeyPress_common(e,AE.treebox,AE.dataarray);
	},
	
	accessext_handle_treebox_header: function() {
		if (AE.treebox.currentIndex < 0 || AE.treebox.currentIndex >= AE.dataarray.length) {
			return;
		}
		
		var findex = AE.treebox.currentIndex;
		var node = AE.dataarray[findex].node;
		if(node == null || AE.mydoc == null) {
			return;
		}
		//SMF 9/20/07 used by accessext_PositionHighlightNode() when the navigation is off screen but the header is visible, highlight the header
		node.relatednode = AE.dataarray[findex].relatednode;
	
		accessext_treeboxScrollAndHighlightNode(); //accessext_scrollAndHighlightNode(node);
		if (AE.treebox.currentIndex < 0 || AE.treebox.currentIndex >= AE.dataarray.length) {
			return;
		}
			
		accessext_setNoteText(findex);
	}
});
	if (AccessibilityExtension.LIB.InitAccessibilityExt) AccessibilityExtension.LIB.InitAccessibilityExt();	
}});



